package org.example.product.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.bouncycastle.pqc.jcajce.provider.qtesla.SignatureSpi;
import org.example.product.domain.MarketCrop;
import org.example.product.domain.Production;
import org.example.product.service.MarketCropService;
import org.example.product.service.ProductionService;
import org.example.product.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductionService productionService;
    @Autowired
    private MarketCropService marketCropService;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("addProduct")
    public Result addProduct(@RequestBody Production production)
    {
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(DigestUtil.md5Hex(production.toString()), "111", 2, TimeUnit.MINUTES);
        if(!absent){
            return Result.fail("请勿重复加工");
        }
        boolean b = productionService.save(production);
        if(b){
            LambdaQueryWrapper<MarketCrop> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MarketCrop::getId,production.getMcid());
            MarketCrop marketCrop = marketCropService.getOne(wrapper);
            marketCropService.removeById(marketCrop.getId());
        }
        return b?Result.success():Result.fail();
    }
    @RequestMapping("list")
    public Result list(@RequestParam(defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,10);
        List<Production> list = productionService.list();
        return Result.success(new PageInfo<>(list));
    }
}
